package com.sqx.modules.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.dao.MsgDao;
import com.sqx.modules.app.dao.UserDao;
import com.sqx.modules.app.entity.Msg;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.datacentre.dao.DataCentreDao;
import com.sqx.modules.datacentre.dao.ShopAdminDao;
import com.sqx.modules.datacentre.entity.SysUserShop;
import com.sqx.modules.file.utils.Md5Utils;
import com.sqx.modules.goods.dao.GoodsShopDao;
import com.sqx.modules.goods.dao.GoodsShopRelevancyDao;
import com.sqx.modules.goods.entity.Goods;
import com.sqx.modules.goods.entity.GoodsShop;
import com.sqx.modules.goods.entity.GoodsShopRelevancy;
import com.sqx.modules.goods.service.GoodsAttrService;
import com.sqx.modules.goods.service.GoodsShopService;
import com.sqx.modules.order.dao.AppOrderDao;
import com.sqx.modules.order.dao.OrderGoodsDao;
import com.sqx.modules.order.entity.OrderGoods;
import com.sqx.modules.order.entity.TbOrder;
import com.sqx.modules.sys.dao.SysUserDao;
import com.sqx.modules.sys.entity.SysUserEntity;
import com.sqx.modules.sys.service.SysUserRoleService;
import com.sqx.modules.utils.fieYun.FeiYunUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class GoodsShopServiceImpl extends ServiceImpl<GoodsShopDao, GoodsShop> implements GoodsShopService {

    @Autowired
    private GoodsShopDao goodsShopDao;
    @Autowired
    private GoodsShopRelevancyDao goodsShopRelevancyDao;
    @Autowired
    private OrderGoodsDao orderGoodsDao;
    @Autowired
    private MsgDao msgDao;
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private AppOrderDao appOrderDao;
    @Autowired
    private DataCentreDao dataCentreDao;
    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private ShopAdminDao shopAdminDao;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private UserDao userDao;
    @Autowired
    private GoodsAttrService goodsAttrService;

    @Override
    @Transactional
    public Result insertGoodsShop(GoodsShop goodsShop) {
        if(StringUtils.isNotEmpty(goodsShop.getSnCode())){
            String s = addPrinter(goodsShop);
            if(!"ok".equals(s)){
                return Result.error(s);
            }
        }
        goodsShop.setShopScore(5.0);
        goodsShop.setShopSales(0);
        goodsShop.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        goodsShop.setStatus(1);
        goodsShop.setErrandMoney(BigDecimal.valueOf(0));
        goodsShop.setDistributionDistance(0.0);
        goodsShop.setPutawayFlag(0);
        goodsShop.setAutoSendOrder(0);
        goodsShop.setAutoAcceptOrder(0);
        goodsShop.setBannedFlag(0);
        baseMapper.insertGoodsShop(goodsShop);

        //添加管理员账号
        SysUserEntity user = new SysUserEntity();
        user.setCreateTime(new Date());
        user.setUsername(goodsShop.getPhone());
        user.setPassword(goodsShop.getPhone());
        user.setPhone(goodsShop.getPhone());
        List<Long> roleIdList = new ArrayList();
        roleIdList.add(12L);
        user.setStatus(1);
        //sha256加密
        String salt = RandomStringUtils.randomAlphanumeric(20);
        user.setPassword(new Sha256Hash(user.getPassword(), salt).toHex());
        user.setSalt(salt);
        user.setUserType(2);
        sysUserDao.insertSysUser(user);
        Long userId = user.getUserId();//返回的主键user_id
        //添加管理员—商铺关联表
        SysUserShop sysUserShop = new SysUserShop();
        sysUserShop.setShopId(goodsShop.getShopId());
        sysUserShop.setUserId(userId);
        shopAdminDao.insert(sysUserShop);
        //保存用户与角色关系
        sysUserRoleService.saveOrUpdate(user.getUserId(), roleIdList);
        //todo 绑定用户和管理用户
        UserEntity userEntity = new UserEntity();
        userEntity.setUserId(goodsShop.getUserId());
        userEntity.setAdminUserId(user.getUserId());
        userEntity.setShopAdminFlag(1);
        userDao.updateById(userEntity);

        return Result.success();
    }


    /**
     * 绑定打印机推送
     *
     * @param goodsShop
     * @return
     */
    public String addPrinter(GoodsShop goodsShop) {
        //目前只有飞鹅pos机可以推送
        if (goodsShop.getFacility()!=null && goodsShop.getFacility().equals(1)) {
            String snlist = goodsShop.getSnCode() + "#" + goodsShop.getValue() + "#" + goodsShop.getShopName();
            String method = FeiYunUtils.addprinter(snlist);
            JSONObject jsonObject = JSON.parseObject(method);
            if (jsonObject != null) {
                if ("0".equals(jsonObject.getString("ret"))) {
                    JSONObject data = jsonObject.getJSONObject("data");
                    JSONArray no = data.getJSONArray("no");
                    if(no.size()>0){
                        return no.getString(0);
                    }
                    return "ok";
                }
                return jsonObject.getString("msg");
            }
            return "pos机添加失败！";
        } else {
            return "ok";
        }
    }



    @Override
    public Result updateGoodsShop(GoodsShop goodsShop) {
        GoodsShop goodsShop1 = goodsShopDao.selectById(goodsShop.getShopId());
        if(StringUtils.isNotEmpty(goodsShop.getSnCode())){
            //判断下本次和上次的一样吗 如果一样则不做校验
            if(StringUtils.isNotEmpty(goodsShop1.getSnCode()) && StringUtils.isNotEmpty(goodsShop1.getValue()) ){
                if(!goodsShop1.getSnCode().equals(goodsShop.getSnCode()) || !goodsShop1.getValue().equals(goodsShop.getValue())){
                    String s = addPrinter(goodsShop);
                    if(!"ok".equals(s)){
                        return Result.error(s);
                    }
                    //删除之前的打印机
                    String snlist = goodsShop1.getSnCode();
                    FeiYunUtils.deletePrinter(snlist);
                }
            }else{
                String s = addPrinter(goodsShop);
                if(!"ok".equals(s)){
                    return Result.error(s);
                }
            }
        }else{
            //判断之前有没有写过打印机 如果写过 则删除
            if(StringUtils.isNotEmpty(goodsShop1.getSnCode())){
                //删除之前的打印机
                String snlist = goodsShop1.getSnCode();
                FeiYunUtils.deletePrinter(snlist);
            }
        }
        if(goodsShop.getBannedFlag().equals(1)){
            goodsShop.setPutawayFlag(1);
            sendMsgDXB(goodsShop.getPhone(), null, 1);
        }
        baseMapper.updateById(goodsShop);
        return Result.success();
    }

    private Result sendMsgDXB(String phone, String value, Integer type) {
        if(type==2){
            Msg byPhone = msgDao.findByPhone(phone);
            if (byPhone != null) {
                byPhone.setCode(String.valueOf(value));
                byPhone.setPhone(phone);
                msgDao.updateById(byPhone);
            } else {
                Msg msg = new Msg();
                msg.setCode(String.valueOf(value));
                msg.setPhone(phone);
                msgDao.insert(msg);
            }
        }
        CommonInfo three = commonInfoService.findOne(164);
        CommonInfo four = commonInfoService.findOne(165);
        CommonInfo name = commonInfoService.findOne(12);
        value = "【" + name.getValue() + "】 您的店铺因违规操作已被封禁，请联系平台客服！";
        String testUsername = three.getValue(); //在短信宝注册的用户名
        String testPassword = four.getValue(); //在短信宝注册的密码
        StringBuilder httpArg = new StringBuilder();
        httpArg.append("u=").append(testUsername).append("&");
        httpArg.append("p=").append(Md5Utils.md5s(testPassword)).append("&");
        httpArg.append("m=").append(phone).append("&");
        httpArg.append("c=").append(Md5Utils.encodeUrlString(value, "UTF-8"));
        String result = Md5Utils.request("https://api.smsbao.com/sms", httpArg.toString());
        log.error("短信包返回值："+result);
        return Result.success();
    }

    @Override
    public Result deleteGoodsShop(Long id) {
        baseMapper.deleteById(id);
        return Result.success();
    }

    @Override
    public Result selectGoodsByShopId(Long shopId, Integer page, Integer limit, String goodsName, Integer classifyId, Integer status) {
        Page<Goods> pages = new Page<>(page, limit);
        PageUtils pageUtils = new PageUtils(goodsShopDao.selectGoodsByShopId(pages, shopId, goodsName, classifyId, status));
        return Result.success().put("data", pageUtils);
    }

    @Override
    public Result selectGoodsByNotShopId(Long shopId, Integer page, Integer limit, String goodsName) {
        Page<Goods> pages = new Page<>(page, limit);
        PageUtils pageUtils = new PageUtils(goodsShopDao.selectGoodsByNotShopId(pages, shopId, goodsName));
        return Result.success().put("data", pageUtils);
    }

    @Override
    public Result addGoodsByShopId(List<GoodsShopRelevancy> goodsShopRelevancyList) {
        String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        goodsShopDao.addGoodsByShopId(goodsShopRelevancyList, date);
        return Result.success();
    }

    @Transactional
    @Override
    public Result deleteGoodsByShopId(Long shopId, Long goodsId) {
        goodsShopDao.deleteGoods(shopId, goodsId);
        goodsShopDao.deleteGoodsByShopId(shopId, goodsId);
        goodsAttrService.deleteGoodsAttr(goodsId);
        return Result.success();
    }

    @Override
    public Result soldOutOrPutaway(Long shopId, Long goodsId, Integer status) {
        goodsShopDao.soldOutOrPutaway(shopId, goodsId,status);
        return Result.success();
    }

    @Override
    public Result updateGoodsByShopId(GoodsShopRelevancy goodsShopRelevancy) {
        goodsShopRelevancyDao.update(goodsShopRelevancy, new QueryWrapper<GoodsShopRelevancy>()
                .eq("shop_id", goodsShopRelevancy.getShopId())
                .eq("goods_id", goodsShopRelevancy.getGoodsId()));
        return Result.success();
    }

    @Override
    public Result selectStoreData(Long shopId, String date, String dateType) {
        HashMap hashMap = new HashMap();
        BigDecimal sumMoney = appOrderDao.selectSumMoney(date, dateType,shopId);
        int countOrder = appOrderDao.selectCountOrder(date, dateType,shopId);
        //到店订单数
        int takeCount = dataCentreDao.selectTakeCount(1, shopId, date, dateType);
        //外卖订单数
        int takeCount2 = dataCentreDao.selectTakeCount(2, shopId, date, dateType);
        //到店订单金额
        BigDecimal takeMoney = dataCentreDao.selectTakeMoney(1, shopId, date, dateType);
        //外卖订单金额
        BigDecimal takeMoney1 = dataCentreDao.selectTakeMoney(2, shopId, date, dateType);
        //退款订单数
        int cancelOrderCount = dataCentreDao.cancelOrderCount(shopId, date, dateType);
        //退款金额
        BigDecimal cancelOrderMoney = dataCentreDao.cancelOrderMoney(shopId, date, dateType);
        hashMap.put("takeCount", takeCount);
        hashMap.put("takeCount2", takeCount2);
        hashMap.put("takeMoney", takeMoney);
        hashMap.put("takeMoney1", takeMoney1);
        hashMap.put("cancelOrderCount", cancelOrderCount);
        hashMap.put("cancelOrderMoney", cancelOrderMoney);
        hashMap.put("count", countOrder);
        hashMap.put("money", sumMoney);
        return Result.success().put("hashMap", hashMap);
    }

    @Override
    public Result selectStoreMessage(Long shopId, String startTime, String endTime, Integer page, Integer limit, String orderNumber) {
        Page<TbOrder> pages = new Page<>(page, limit);
        IPage<TbOrder> tbOrderIPage = goodsShopDao.selectStoreMessage(pages, shopId, startTime, endTime, orderNumber);
        List<TbOrder> records = tbOrderIPage.getRecords();
        for(int i = 0;i<records.size();i++){
            List<OrderGoods> orderGoodsList = orderGoodsDao.selectList(new QueryWrapper<OrderGoods>()
                    .eq("order_id", records.get(i).getOrderId()));
            tbOrderIPage.getRecords().get(i).setOrderGoodsList(orderGoodsList);
        }
        PageUtils pageUtils = new PageUtils(tbOrderIPage);
        return Result.success().put("data", pageUtils);
    }


}
